<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-03-22
 * Time: 12:57
 */

namespace App\Services\Impl;


use App\Services\IStorageService;
use Illuminate\Support\Str;
use Illuminate\Http\File;
use Storage;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;

class LocalStorageServiceImpl implements IStorageService
{
    /**
     * 是否按日期划分文件夹
     */
    private $daily = true;

    private $directory = '/';

    private $unknown_extension = 'unk';

    public function __construct()
    {
        if ($this->daily){
            $this->directory .= date('Ymd/');
        }
    }

    public function saveUpload($key)
    {
        $file = request()->file($key);
        if (!$file){
            return false;
        }
        $filename = $file->hashName();
        if (!\File::extension($filename)){
            $filename .= $this->unknown_extension;
        }
        $directory = trim($this->directory, '/');
        $path = Storage::disk('local')->putFileAs($directory, $file, $filename);
        return $path ? '/'.$path: false;
    }

    public function saveFile($path)
    {
        $file = new File($path);
        if (!$file->isFile()){
            return false;
        }
        $filename = $file->hashName();
        if (!\File::extension($filename)){
            $filename .= \File::extension($path);
        }
        $directory = trim($this->directory, '/');
        $path = Storage::disk('local')->putFileAs($directory, $file, $filename);
        return $path ? '/'.$path: false;
    }

    public function saveStream($binary_stream)
    {
        $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $binary_stream);
        $guesser = ExtensionGuesser::getInstance();
        $extension = $guesser->guess($mime) ? : $this->unknown_extension;
        $fullname = sprintf('%s%s.%s',$this->directory,Str::random(40),$extension);
        return Storage::disk('local')->put($fullname, $binary_stream) ? $fullname : false;
    }

    public function saveUrl($url)
    {
        $extension = \File::extension($url) ? : $this->unknown_extension;
        $fullname = sprintf('%s%s.%s',$this->directory,Str::random(40),$extension);
        return Storage::disk('local')->put($fullname, fopen($url,'r')) ? $fullname : false;
    }

    public function getRealPath($path)
    {
        return Storage::disk('local')->getDriver()->getAdapter()->applyPathPrefix($path);
    }

    public function getUrl($path)
    {
        return route('uploaded',['path'=>$path]);
    }

    public function getUri($path)
    {
        $url = route('uploaded',['path'=>$path]);
        return substr($url,strpos($url,'/',10));
    }

    public function fileExists($path)
    {
        return Storage::disk('local')->exists($path);
    }

    public function getContent($path)
    {
        return Storage::get($path);
    }

    public function getResponse($path)
    {
        return response()->file($this->getFilePath($path));
    }

}